package com.luom.usercenter.controller;

import com.luom.usercenter.common.BaseResponse;
import com.luom.usercenter.common.ErrorCode;
import com.luom.usercenter.common.ResultUtils;
import com.luom.usercenter.exception.BusinessException;
import com.luom.usercenter.model.User;
import com.luom.usercenter.model.request.UserDeleteRequest;
import com.luom.usercenter.model.request.UserLoginRequest;
import com.luom.usercenter.model.request.UserRegisterRequest;
import com.luom.usercenter.model.request.UserUpdateRequest;
import com.luom.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.luom.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.luom.usercenter.contant.UserConstant.USER_LOGIN_STATE;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册接口
     * @param userRegisterRequest 用户注册实体
     * @return 注册用户id
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String password = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, password, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long l = userService.userRegister(userAccount, password, checkPassword);
        return ResultUtils.success(l);
    }

    /**
     * 用户登录
     * @param userLoginRequest 用户登录实体
     * @param request HttpServletRequest
     * @return 脱敏后用户信息
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        log.info(userLoginRequest.toString());
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        System.out.println(user.toString());
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"request==null");
        }
        Integer i = userService.userLogout(request);
        return ResultUtils.success(i);
    }

    /**
     * 按照用户名查找
     * @param username 用户名
     * @param request HttpServletRequest
     * @return 用户集合
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        //鉴权
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (username==null) {
            List<User> userList = userService.searchAllUsers(null);
            return ResultUtils.success(userList);
        }
        List<User> userList = userService.searchUsers(username);
        List<User> collect = userList.stream().map(user -> userService.getSafetUser(user)).collect(Collectors.toList());
        return ResultUtils.success(collect);
    }

    /**
     * 删除用户
     * @param request HttpServletRequest
     * @return 是否删除成功
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody UserDeleteRequest userDeleteRequest, HttpServletRequest request) {
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (userDeleteRequest.getId() <= 0)
            return null;
        boolean b = userService.deleteUser(userDeleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 获取用户登录态
     * @param request HttpServletRequest
     * @return 登录用户信息
     */
    @GetMapping("/current")
    public BaseResponse<User> currentUser(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user==null){
            return null;
        }
        user=userService.getById(user.getId());
        return ResultUtils.success(user);
    }


    /**
     * 是否为管理员
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user==null||user.getUserRole()!=ADMIN_ROLE)
            return false;
        return true;
    }

    /**
     * 更新用户
     * @param userUpdateRequest 更新用户实体
     * @param request
     * @return 是否更新成功
     */
    @PostMapping("/update")
    private BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,HttpServletRequest request){
        log.info(userUpdateRequest.toString());
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (userUpdateRequest.getId()==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        userService.updateUser(userUpdateRequest);
        return ResultUtils.success(true);
    }


}
